package com.itheima.sky.controller.front;

import com.itheima.sky.constant.MessageConstant;
import com.itheima.sky.constant.RedisMessageConstant;
import com.itheima.sky.entity.Result;
import com.itheima.sky.pojo.User;
import com.itheima.sky.service.UserService;
import com.itheima.sky.utils.DateUtils;
import com.itheima.sky.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description UserController
 * @Author jiangning
 * @Date 2024-06-27
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/sendMsg")
    public Result sendSMSCode(@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        String code = userService.generateSmsCode(phone);
        log.info(phone+" 的验证码："+code);
        Result r = Result.success(null);
        r.setMsg(MessageConstant.SEND_VALIDATECODE_SUCCESS);
        return r;
    }

    @PostMapping("/login")
    public Result login(@RequestBody Map<String,String> map, HttpSession session){
        String code = map.get("code");
        String phone = map.get("phone");
        userService.verifySmsCode(phone,code);
        Long userId = userService.getUserIdByPhone(phone);
        if(userId==null){
            User user = new User();
            user.setPhone(phone);
            userId = userService.insertUser(user);
        }
        session.setAttribute("userId",userId);
        return Result.success(null);
    }

    @GetMapping("/test")
    public String test(){
        return "its ok";
    }
}
